const { role } = require('../models/mrole');
const Joi = require('joi');
const validationMiddleware = require('../middleware/validate');
const response = require("../utils/response");
const router = require('koa-router')();
const { dealNotEmpty, dealNotEmptyArry, handleDatabaseError } = require("../utils/dberrordeal");

const rulesSchema = {
    '/addrole': Joi.object({
        name: dealNotEmpty('名称'),
        roles: dealNotEmptyArry('角色权限')
    }),
    '/putrole': Joi.object({
        id: dealNotEmpty('id'),
        name: dealNotEmpty('名称'),
        roles: dealNotEmptyArry('角色权限')
    }),
    '/delrole': Joi.object({
        id: dealNotEmpty('id')
    }),
    '/getrolei': Joi.object({
        id: dealNotEmpty('id')
    })
};

router.post('/addrole', validationMiddleware(rulesSchema), async (ctx, next) => {
    let data = ctx.request.body;
    await role.create(data).then((res) => {
        response.success(ctx, {});
    }).catch(err => {
        handleDatabaseError(ctx, err, "角色名称已存在");
    }
    );
});

router.post('/putrole', validationMiddleware(rulesSchema), async (ctx, next) => {
    let data = ctx.request.body;
    await role.findOneAndUpdate({ _id: data.id }, { $set: data }).then(res => {
        response.success(ctx, {});
    }).catch(err => {
        response.error(ctx, {});
    });
});


router.post('/getrolei', validationMiddleware(rulesSchema), async (ctx, next) => {
    let data = ctx.request.body;
    await role.findOne({ _id: data.id }).then(res => {
        response.success(ctx, { data: res });
    }).catch(err => {
        response.error(ctx, {});
    });
});

router.get('/rolelist', async (ctx, next) => {
    await role.find().sort({order:1}) .populate('roles', 'name path isMenu order parentId alias').exec().then(res => {
        response.success(ctx, { data: res });
    }).catch(err => {
        response.error(ctx, {});
    });
});

router.post('/delrole', validationMiddleware(rulesSchema), async (ctx, next) => {
    let data = ctx.request.body;
    await role.findOneAndDelete({ _id: data.id }).then(res => {
        response.success(ctx, {});
    }).catch(err => {
        response.error(ctx, {});
    });
});

module.exports = router;
